import os
import time
import json
from django.forms.models import model_to_dict
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth.hashers import make_password, check_password

from apps.base.status import *
from apps.base.colors import ROLE_COLOR
from apps.base.validation import user_validation, is_superuser
from apps.base.login_register import check_login, LoginForm, RegisterForm

from .models import User, Role


def register(request):
    """
    用户注册
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, 'register.html')
    elif request.method == "POST":
        result = {"status": HTTP_500_INTERNAL_SERVER_ERROR, "message": None, "data": None}
        user_register_form = RegisterForm(request, request.POST)
        if user_register_form.is_valid():
            username = user_register_form.cleaned_data.get("username")
            fullname = user_register_form.cleaned_data.get("fullname")
            phone = user_register_form.cleaned_data.get("phone")
            password = user_register_form.cleaned_data.get("password")

            " 保存用户信息到数据库 "
            if User.objects.filter(username=username):
                result["message"] = "该用户名已注册,登录或者更换用户名！"
            else:
                try:
                    user_obj = User.objects.create(
                        username=username,
                        fullname=fullname,
                        phone=phone,
                        password=make_password(password)
                    )

                    user_obj.is_superuser = False
                    user_obj.save()
                except Exception as e:
                    print(e)
                    result["message"] = "注册失败,请联系管理员！"
                else:
                    result["status"] = HTTP_200_OK
                    result["message"] = "用户注册成功..."
        else:
            " 表单验证失败 "
            result["message"] = user_register_form.errors

        return HttpResponse(json.dumps(result))


def login(request):
    """
    用户登录
    :param request:
    :return:
    """
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        temp_dict = {}
        result = {"status": HTTP_500_INTERNAL_SERVER_ERROR, "message": None, "data": None}
        user_login_form = LoginForm(request, request.POST)
        if user_login_form.is_valid():
            username = user_login_form.cleaned_data.get("username")
            password = user_login_form.cleaned_data.get("password")

            user_info = User.objects.filter(username=username).first()
            if user_info and check_password(password, user_info.password):
                temp_dict["username"] = user_info.username
                temp_dict["fullname"] = user_info.fullname
                temp_dict["bio"] = user_info.bio
                temp_dict["phone"] = user_info.phone
                temp_dict["avatar"] = user_info.avatar
                temp_dict["is_superuser"] = user_info.is_superuser
                request.session["user_info"] = temp_dict
                result["status"] = HTTP_200_OK
            else:
                result["message"] = "账号密码不匹配！"

        else:
            " 表单验证失败 "
            result["message"] = user_login_form.errors
        return HttpResponse(json.dumps(result))


def logout(request):
    """
    登出
    :param request:
    :return:
    """
    request.session.set_expiry = 1
    request.session.clear()
    return redirect("/")


@check_login
def profile(request, username):
    pass


@check_login
def change_password(request, username):
    """
    修改用户密码
    :param request:
    :param username:
    :return:
    """
    if request.method == "POST":
        result = {"status": HTTP_500_INTERNAL_SERVER_ERROR, "message": None, "data": None}
        current_password = request.POST.get("current_password")
        new_password = request.POST.get("new_password")
        anew_password = request.POST.get("anew_password")
        "校验密码"
        user_info = User.objects.get(username=username)
        if user_info and check_password(current_password, user_info.password):
            if new_password == anew_password and new_password and len(new_password) >= 6:
                "更新数据库密码"
                try:
                    user_info.password = make_password(new_password)
                    user_info.save()
                except Exception as e:
                    print(e)
                    result["message"] = "密码更新失败..."
                else:
                    result["status"] = HTTP_200_OK
                    result["message"] = "密码更新成功..."
            else:
                result["message"] = "新密码不统一或者格式不正确..."
        else:
            result["message"] = "旧密码不正确..."
        return HttpResponse(json.dumps(result))
